package cn.zd.demo1;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Random;

public class PostActivity extends AppCompatActivity implements View.OnClickListener {

    private static int not_id = 0;
    private static int progresscount = 0;
    private static int progressnoticeid = 0;
    private static NotificationCompat.Builder mBuilder;
    private static NotificationManagerCompat notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.btn_active_post);
        Toast.makeText(this, this.getClass().getName(), Toast.LENGTH_LONG).show();

        findViewById(R.id.btn_1).setOnClickListener(this);
        findViewById(R.id.btn_2).setOnClickListener(this);
        findViewById(R.id.btn_3).setOnClickListener(this);
        findViewById(R.id.btn_4).setOnClickListener(this);
        TextView tv = findViewById(R.id.tv_1);

        tv.setText("传递参数内容："+(getIntent() == null?"":getIntent().getIntExtra("code",-1)+":"+getIntent().getStringExtra("msg")));
        new Thread(() -> {
            while (true) {
                if(progressnoticeid != 0) {
                    progresscount += new Random().nextInt(10);
                    if (progresscount > 100) {
                        progresscount = 100;
                    }
                    if (notificationManager != null && mBuilder != null) {
                        mBuilder.setProgress(100, progresscount, false);
                        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        notificationManager.notify(progressnoticeid, mBuilder.build());
                    }
                    if (progresscount >= 100) {
                        progresscount = 0;
                        mBuilder.setProgress(0, 0, false);
                        notificationManager.notify(progressnoticeid, mBuilder.build());
                        progressnoticeid = 0;
                    }
                }
                try {
                    Thread.sleep(600);
                } catch (InterruptedException e) {

                }

            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_1) {
            push(-1l, true);


            /*NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,(String) null)
                    .setContentTitle("这是标题")
                    .setContentText("我是内容，我是demo")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

            //通过 builder.build() 拿到 notification
            mNotificationManager.notify(1, mBuilder.build());*/
            Toast.makeText(this, "推送文字消息", Toast.LENGTH_SHORT).show();
        }
        if (v.getId() == R.id.btn_2) {
            push(5000l, true);
        }
        if (v.getId() == R.id.btn_3) {
            push(5000l, false);
        }
        if (v.getId() == R.id.btn_4) {
            push(0l, false,true);
        }
    }

    private boolean push(long autoCancel, boolean ongoing) {
        return push(autoCancel,ongoing,false);
    }
    private boolean push(long autoCancel, boolean ongoing, boolean progress) {
        not_id++;
        notificationManager = NotificationManagerCompat.from(this);
        // 在 MainActivity 或其他合适的地方创建通知渠道
        String channelId = "001";   //通知渠道的标识符
        CharSequence channelName = "Android学习Demo";    //通知渠道的位置
        String channelDescription = "Android学习通知";    //通知渠道的描述

        //创建通知渠道
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT); //设置通知渠道的级别
        notificationChannel.setShowBadge(true);
        notificationChannel.setDescription(channelDescription);//可以省略


        //在系统中注册消息
        notificationManager.createNotificationChannel(notificationChannel);


        // 构建配置
        mBuilder = new NotificationCompat.Builder(this, channelId)
                .setContentTitle("这是标题:" + not_id)
                .setContentText("我是内容，我是demo:" + not_id + " 可被清除：" + ongoing + " 自动消失：" + autoCancel)
                .setWhen(System.currentTimeMillis())
                .setSound(Uri.fromFile(new File("/system_ext/media/audio/alarms/Dynamic_Weather.ogg")))// 通知铃声
                .setPriority(NotificationCompat.PRIORITY_HIGH) // 7.0 设置优先级
                .setVibrate(new long[]{0, 1000, 1000, 1000})// 震动 .setDefaults(NotificationCompat.DEFAULT_VIBRATE)
                .setLights(Color.RED, 1000, 1000) // led .setDefaults(NotificationCompat.DEFAULT_LIGHTS)
                .addAction(R.drawable.android9, "打开1", pendingIntent(not_id,"点击了按钮1@通知id："+not_id))
                .addAction(R.drawable.android10, "打开2", pendingIntent(not_id,"点击了按钮2@通知id："+not_id))
                .setOngoing(ongoing)// 设置通知栏能否被清楚，true不能被清除，false可以被清除
                .setContentIntent(pendingIntent(not_id,"消息被点击按钮@通知id："+not_id)) // 跳转配置
                .setSmallIcon(not_id % 2 == 0 ? R.drawable.android1 : R.drawable.android10) //小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), not_id % 2 == 0 ? R.drawable.android3 : R.drawable.android5));
        if (autoCancel < 1L) {
            mBuilder.setAutoCancel(true);// 是否自动消失（点击）or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()
        } else {
            mBuilder.setTimeoutAfter(autoCancel);
        }
        if(progress) {
            progressnoticeid = not_id;
            mBuilder.setProgress(100, progresscount, false);
        }
        // 发起通知
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "请先开启权限", Toast.LENGTH_SHORT).show();
            return true;
        }
        // channelId非常重要，不设置通知栏不展示
        mBuilder.setChannelId(channelId);
        notificationManager.notify(not_id, mBuilder.build());
        return false;
    }

    public PendingIntent pendingIntent( int requestCode,String data) {
        // 点击意图 // setDeleteIntent 移除意图
        Intent intent = new Intent(this, PostActivity.class);
        intent.putExtra("msg",data);
        intent.putExtra("code",requestCode);
      return PendingIntent.getActivity(this,requestCode,intent,PendingIntent.FLAG_IMMUTABLE);
    }
}